package action;

import java.awt.event.ActionEvent;
import java.io.IOException;

import javax.swing.AbstractAction;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

import modeles.Contact;
import controller.ControllerTab;
import utilitaire.ListContact;
import utilitaire.MyFile;
import vues.EditContactWindow;
import vues.HomeWindow;
import vues.NewContactWindow;

/**
 * 
 * Class Action Suppression de contact
 * editContact	Objet EditContactWindow
 * homeView		Objet HomeWindow
 * modele		Objet ControllerTab
 * idContact	Objet int
 * 
 * @author Paul BEZARD-FALGAS
 *
 */
public class ActionUpdateContact extends AbstractAction {

	private static final long serialVersionUID = 1L;
	private EditContactWindow editContact;
	private HomeWindow homeView;
	private ControllerTab modele;
	private int idContact;

	public ActionUpdateContact(HomeWindow home, EditContactWindow editContactWindow, ControllerTab mod, int id){
		super();
		this.homeView = home;
		this.editContact = editContactWindow;
		this.modele = mod;
		this.idContact = id;
	}	  


	public void actionPerformed(ActionEvent e){
		SwingUtilities.invokeLater(new Runnable(){
			public void run(){
				JOptionPane jop1;
				boolean save = false;
				Contact contact = new Contact();
				
				contact.setName(editContact.getField1());
				contact.setFirstName(editContact.getField2());
				contact.setCompanyAddress(editContact.getField3());
				contact.setPersonalPhone(editContact.getField4());
				contact.setProfessionalPhone(editContact.getField5());
				contact.setHomePage(editContact.getField6());
				contact.setEmail(editContact.getField7());
				contact.setPicture(editContact.getField8());
				contact.setOther(editContact.getField9());
				contact.setGroup(editContact.getSelectedGrp());
				
				//Suppression de la liste du contact
	            modele.getList().remove(idContact);
	            
	            //Ajout de la liste du nouveau contact
				modele.getList().add(contact);
				
				//Ecriture du contact dans le fichier txt
				MyFile file = new MyFile();
				try {
					save = file.rewriteAllContact(modele.getList());
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				
				//Test si la sauvegarde a r�ussi
				if(save)
				{					
					//Boite du message d'information
					jop1 = new JOptionPane();
					jop1.showMessageDialog(null, "Update Success", "Information", JOptionPane.INFORMATION_MESSAGE); 
				}else{
					//Boite du message d'erreur
					jop1 = new JOptionPane();
					jop1.showMessageDialog(null, "Error with contact", "Erreur", JOptionPane.ERROR_MESSAGE);
				}
			}
		});
	}

}
